<?php

namespace Reusify\Helper;

class ArrayHelper
{
    public static function tree($list, $pid = 0, $level = 1, $idKey = 'id', $pidKey = 'pid', $childKey = 'child'): array
    {
        $tree = [];
        foreach ($list as &$v)
        {
            if ($v[$pidKey] != $pid) continue;
            $son = self::tree($list, $v[$idKey], $level + 1, $idKey, $pidKey, $childKey);
            $v[$childKey] = $son;
            $tree[] = $v;
        }
        return $tree;
    }

    /**
     * 数组分页处理
     * @param array $array
     * @param int $page
     * @param int $perPage
     * @return array
     */
    public static function paginate(array $array, int $page = 1, int $perPage = 15): array
    {
        $offset = ($page - 1) * $perPage;
        return array_slice($array, $offset, $perPage, true);
    }
}